//    Copyright (C) Kherty.  All rights reserved.
using System;
using OpenLS.Spreadsheet.Extensibility;

namespace OpenLS.Spreadsheet.AnalysisToolPak
{
    internal class Unit : UnitBase
    {
        private readonly double factor = 1.0;
        private readonly Unit ReferenceUnit;

        public Unit(Multiplier m, Unit referenceUnit) : base(m.Prefix + referenceUnit.Name)
        {
            ReferenceUnit = referenceUnit;
            factor = m.Value;
            while (ReferenceUnit.ReferenceUnit != ReferenceUnit)
            {
                factor = factor*ReferenceUnit.Factor;
                ReferenceUnit = ReferenceUnit.ReferenceUnit;
            }
        }

        public Unit(string name) : base(name)
        {
            ReferenceUnit = this;
        }

        public Unit(string name, double factor, Unit referenceUnit) : base(name)
        {
            Unit u = referenceUnit.ReferenceUnit;
            if (u != referenceUnit)
            {
                this.factor = factor*referenceUnit.ConvertTo(1, u);
                ReferenceUnit = u;
            }
            else
            {
                this.factor = factor;
                ReferenceUnit = referenceUnit;
            }
        }

        public double Factor
        {
            get { return factor; }
        }

        public override double ConvertTo(double value, UnitBase o)
        {
            Unit other = o as Unit;
            if (other == null)
                throw new NotSupportedException();
            if (other.ReferenceUnit == ReferenceUnit)
                return value*factor/other.factor;
            throw new ErrorException(Errors.NaError);
        }
    }
}